package com.coolbi.security.web.oauth;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import com.coolbi.security.biz.RoleToUrlBiz;
import com.coolbi.security.biz.RolesBiz;
import com.coolbi.security.entity.RoleUrl;
import com.coolbi.security.entity.Roles;

/**
 * @Description 取到所有资源及其对应角色的定义 此类在初始化时，应该取到所有资源及其对应角色的定义
 * @author for2cold
 * 
 */
public class InvocationSecurityMetadataSourceService implements
		FilterInvocationSecurityMetadataSource {

	@Autowired
	private RolesBiz rolesBiz;
	public void setRolesBiz(RolesBiz rolesBiz) {
		this.rolesBiz = rolesBiz;
	}

	@Autowired
	private RoleToUrlBiz roleToUrlBiz;

	public void setRoleToUrlBiz(RoleToUrlBiz roleToUrlBiz) {
		this.roleToUrlBiz = roleToUrlBiz;
	}

	/** 存放资源 */
	private static Map<String, Collection<ConfigAttribute>> resourceMap = new HashMap<String, Collection<ConfigAttribute>>();

	/** 通过数据库获取所有角色、资源信息，并放入Map中 */
	public void loadResourceDefine() {
		resourceMap.clear();
		Collection<ConfigAttribute> attrs = null;
		ConfigAttribute configAttribute = null;
		for (Roles role : rolesBiz.list()) {
			configAttribute = new SecurityConfig(role.getAuthority());
			List<RoleUrl> roleUrls = roleToUrlBiz.findUrlByRoleId(role.getId());
			for (RoleUrl url : roleUrls) {
				if (resourceMap.containsKey(url.getUrl())) {
					attrs = resourceMap.get(url.getUrl());
					attrs.add(configAttribute);
				} else {
					attrs = new ArrayList<ConfigAttribute>();
					attrs.add(configAttribute);
				}
				resourceMap.put(url.getUrl(), attrs);
			}
		}
	}

	/** 根据请求URL返回具有访问该URL的角色 */
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		/*String requestUrl = ((FilterInvocation) object).getRequestUrl();
		int subIndex = requestUrl.indexOf("?");
        if (subIndex == -1) {
        	subIndex = requestUrl.length();
        }
        requestUrl = requestUrl.substring(1, subIndex);
		String regex = "^(admin).*(.action)$";
		if (requestUrl.matches(regex)) {
			if (resourceMap.isEmpty()) {
				loadResourceDefine();
			}
			return resourceMap.get(requestUrl);
		}*/
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}
}
